#!/usr/bin/env python3
"""
真实数据采集版本 - 支持真实IMU和声音波形
1. 更新IP地址为192.168.10.101
2. 实现真实IMU振动数据采集
3. 实现真实声音波形数据采集
"""

def create_real_data_version():
    # 读取当前文件
    with open('web_bearing_monitor_emergency_fix.py', 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 1. 更新IP地址
    content = content.replace('192.168.1.5', '192.168.10.101')
    content = content.replace('http://127.0.0.1:', 'http://192.168.10.101:')
    
    # 2. 实现真实IMU数据采集
    real_vibration_monitor = '''    def vibration_monitor(self):
        """振动监控线程 - 真实IMU数据采集"""
        self.logger.info("启动振动监控线程")
        
        # 检查gatt模块和IMU设备
        imu_available = False
        imu_process = None
        
        try:
            # 尝试导入gatt模块
            try:
                import gatt
                self.logger.info("✅ gatt模块可用，尝试连接IMU设备...")
                imu_available = True
            except ImportError:
                self.logger.warning("❌ gatt模块不可用，安装中...")
                # 尝试安装gatt相关模块
                import subprocess
                try:
                    subprocess.run([sys.executable, '-m', 'pip', 'install', 'pygatt', 'bluepy'], 
                                 check=True, capture_output=True)
                    import gatt
                    imu_available = True
                    self.logger.info("✅ gatt模块安装成功")
                except:
                    self.logger.error("❌ 无法安装gatt模块，使用模拟数据")
                    imu_available = False
            
            if imu_available:
                # 启动真实IMU进程
                self.logger.info(f"启动IMU进程，MAC地址: 26:EF:60:96:87:3A")
                imu_process = subprocess.Popen(
                    [sys.executable, "imu_node.py", "26:EF:60:96:87:3A"],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    text=True,
                    bufsize=1
                )
                
                # 等待IMU连接建立
                self.logger.info("等待IMU蓝牙连接建立...")
                for i in range(15):
                    time.sleep(1)
                    if imu_process.poll() is not None:
                        stdout, stderr = imu_process.communicate()
                        self.logger.error(f"IMU进程退出: {stderr}")
                        imu_available = False
                        break
                    if i == 5:
                        self.logger.info("IMU连接中，请稍候...")
                
                if imu_available and imu_process.poll() is None:
                    self.logger.info("✅ IMU连接成功，开始读取真实数据")
                else:
                    self.logger.warning("❌ IMU连接失败，切换到模拟模式")
                    imu_available = False
        
        except Exception as e:
            self.logger.error(f"IMU初始化失败: {e}")
            imu_available = False
        
        # 主监控循环
        data_line = ""
        while self.running:
            try:
                timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
                
                if imu_available and imu_process and imu_process.poll() is None:
                    # 读取真实IMU数据
                    try:
                        import select
                        if select.select([imu_process.stdout], [], [], 0.1)[0]:
                            line = imu_process.stdout.readline().strip()
                            if line:
                                # 解析IMU数据行
                                vibration_data = self._parse_real_imu_data(line)
                                if vibration_data:
                                    self._process_vibration_data(vibration_data, timestamp, True)
                                    continue
                    except Exception as e:
                        self.logger.debug(f"IMU数据读取错误: {e}")
                
                # 生成模拟数据（作为备用）
                vibration_data = self._generate_simulated_vibration()
                self._process_vibration_data(vibration_data, timestamp, False)
                
                time.sleep(0.1)
                
            except Exception as e:
                self.logger.error(f"振动监控错误: {e}")
                time.sleep(1)
        
        # 清理IMU进程
        if imu_process and imu_process.poll() is None:
            try:
                imu_process.terminate()
                imu_process.wait(timeout=3)
                self.logger.info("IMU进程已停止")
            except:
                try:
                    imu_process.kill()
                except:
                    pass
    
    def _parse_real_imu_data(self, line):
        """解析真实IMU数据"""
        try:
            # 假设IMU输出格式: ax,ay,az,gx,gy,gz 或类似格式
            parts = line.split(',')
            if len(parts) >= 6:
                ax = float(parts[0].strip())
                ay = float(parts[1].strip())
                az = float(parts[2].strip())
                gx = float(parts[3].strip())
                gy = float(parts[4].strip())
                gz = float(parts[5].strip())
                
                return {
                    'ax': ax, 'ay': ay, 'az': az,
                    'gx': gx, 'gy': gy, 'gz': gz,
                    'magnitude': math.sqrt(ax**2 + ay**2 + az**2)
                }
            # 尝试其他可能的格式
            elif len(parts) >= 3:
                ax = float(parts[0].strip())
                ay = float(parts[1].strip()) 
                az = float(parts[2].strip())
                
                return {
                    'ax': ax, 'ay': ay, 'az': az,
                    'gx': 0, 'gy': 0, 'gz': 0,
                    'magnitude': math.sqrt(ax**2 + ay**2 + az**2)
                }
        except (ValueError, IndexError) as e:
            self.logger.debug(f"IMU数据解析失败: {line} -> {e}")
            return None
        return None
    
    def _generate_simulated_vibration(self):
        """生成模拟振动数据"""
        import time
        time_offset = time.time() * 10
        
        ax = 0.5 * math.sin(2.0 * time_offset) + random.uniform(-0.1, 0.1)
        ay = 0.3 * math.cos(2.4 * time_offset) + random.uniform(-0.1, 0.1)
        az = 0.2 * math.sin(1.6 * time_offset) + random.uniform(-0.1, 0.1)
        
        # 随机异常
        if random.random() < 0.05:
            ax *= 3
            ay *= 3
            az *= 3
        
        gx = random.uniform(-0.05, 0.05)
        gy = random.uniform(-0.05, 0.05)
        gz = random.uniform(-0.05, 0.05)
        
        return {
            'ax': ax, 'ay': ay, 'az': az,
            'gx': gx, 'gy': gy, 'gz': gz,
            'magnitude': math.sqrt(ax**2 + ay**2 + az**2)
        }
    
    def _process_vibration_data(self, vibration_data, timestamp, is_real):
        """处理振动数据"""
        vibration_data['timestamp'] = timestamp
        vibration_data['is_real'] = is_real
        
        self.vibration_queue.put(vibration_data)
        
        # 添加到Web缓冲区
        self.web_buffer.add_data(timestamp, vibration=vibration_data['magnitude'], is_waveform=True)
        
        # 通过WebSocket发送实时数据
        self.socketio.emit('vibration_data', {
            'timestamp': timestamp,
            'magnitude': vibration_data['magnitude'],
            'ax': vibration_data['ax'], 
            'ay': vibration_data['ay'], 
            'az': vibration_data['az'],
            'gx': vibration_data['gx'], 
            'gy': vibration_data['gy'], 
            'gz': vibration_data['gz'],
            'is_real': is_real
        })
        
        # 异常检测
        if vibration_data['magnitude'] > self.vibration_threshold:
            self._log_anomaly('vibration', 'high',
                            f"轴承振动异常: {vibration_data['magnitude']:.3f}g", 
                            0, vibration_data['magnitude'], 0)'''
    
    # 3. 实现真实声音波形数据采集
    real_audio_monitor = '''    def audio_monitor(self):
        """音频监控线程 - 真实声音波形数据采集"""
        self.logger.info("启动音频监控线程")
        
        # 启动录音进程
        rec_process = None
        try:
            self.logger.info("启动录音数据采集进程...")
            rec_process = subprocess.Popen(
                [sys.executable, "rec.py"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
            time.sleep(2)
            
            if rec_process.poll() is not None:
                stdout, stderr = rec_process.communicate()
                self.logger.error(f"录音进程启动失败: {stderr}")
                rec_process = None
            else:
                self.logger.info("✅ 录音进程启动成功")
        except Exception as e:
            self.logger.error(f"无法启动录音进程: {e}")
            rec_process = None
        
        while self.running:
            try:
                timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
                
                # 检查录音文件并分析真实音频
                recordings_dir = "recordings"
                latest_file = None
                use_real_audio = False
                
                if rec_process and os.path.exists(recordings_dir):
                    audio_files = [f for f in os.listdir(recordings_dir) 
                                 if f.endswith('.wav') and os.path.getmtime(os.path.join(recordings_dir, f)) > time.time() - 10]
                    if audio_files:
                        latest_file = os.path.join(recordings_dir, sorted(audio_files)[-1])
                        use_real_audio = True
                
                if use_real_audio and latest_file:
                    # 分析真实音频文件
                    audio_result = self._analyze_real_audio_file(latest_file)
                    waveform_data = audio_result['waveform']
                    is_anomaly = audio_result['is_anomaly']
                    anomaly_score = audio_result['anomaly_score']
                    
                    self.logger.debug(f"真实音频分析 - 文件: {os.path.basename(latest_file)}, "
                                    f"能量: {audio_result['energy']:.4f}, "
                                    f"峰值: {audio_result['peak_amplitude']:.4f}, "
                                    f"异常分数: {anomaly_score:.3f}")
                else:
                    # 生成模拟音频数据
                    waveform_data = self._generate_simulated_audio_waveform()
                    anomaly_score = random.uniform(0.1, 0.4)  # 降低模拟数据的异常分数
                    is_anomaly = anomaly_score > 0.7
                
                # 音频数据对象
                audio_data = {
                    'timestamp': timestamp,
                    'filename': os.path.basename(latest_file) if latest_file else f'simulated_{datetime.now().strftime("%H%M%S")}.wav',
                    'is_anomaly': bool(is_anomaly),
                    'anomaly_score': float(anomaly_score),
                    'waveform': waveform_data,
                    'is_real': use_real_audio
                }
                
                self.audio_queue.put(audio_data)
                
                # 添加到Web缓冲区
                self.web_buffer.add_data(timestamp, audio=anomaly_score, is_waveform=True)
                
                # 通过WebSocket发送实时数据
                self.socketio.emit('audio_data', {
                    'timestamp': timestamp,
                    'filename': audio_data['filename'],
                    'is_anomaly': bool(is_anomaly),
                    'score': float(anomaly_score),
                    'waveform': waveform_data[:100] if waveform_data else [],  # 限制数据量
                    'is_real': use_real_audio
                })
                
                if is_anomaly:
                    self._log_anomaly('audio', 'medium',
                                    f"声音异常检测: 分数={anomaly_score:.3f} ({'真实' if use_real_audio else '模拟'})", 
                                    0, 0, anomaly_score)
                
                time.sleep(1.0)
                
            except Exception as e:
                self.logger.error(f"音频监控错误: {e}")
                time.sleep(1)
        
        # 清理录音进程
        if rec_process and rec_process.poll() is None:
            try:
                rec_process.terminate()
                rec_process.wait(timeout=2)
                self.logger.info("录音进程已停止")
            except:
                try:
                    rec_process.kill()
                except:
                    pass
    
    def _analyze_real_audio_file(self, audio_file):
        """分析真实音频文件，提取波形和特征"""
        try:
            import wave
            import numpy as np
            
            with wave.open(audio_file, 'rb') as wav_file:
                frames = wav_file.readframes(wav_file.getnframes())
                sample_rate = wav_file.getframerate()
                
                # 转换为numpy数组
                if wav_file.getsampwidth() == 2:
                    audio_data = np.frombuffer(frames, dtype=np.int16)
                else:
                    audio_data = np.frombuffer(frames, dtype=np.uint8)
                
                # 处理立体声
                if wav_file.getnchannels() == 2:
                    audio_data = audio_data[::2]
                
                # 归一化到-1到1
                if len(audio_data) > 0:
                    max_val = np.iinfo(audio_data.dtype).max
                    audio_data = audio_data.astype(np.float32) / max_val
                else:
                    audio_data = np.array([0])
            
            # 计算音频特征
            energy = np.sqrt(np.mean(audio_data ** 2))  # RMS能量
            peak_amplitude = np.max(np.abs(audio_data))  # 峰值振幅
            
            # 降采样波形数据用于显示（保留真实特征）
            if len(audio_data) > 500:
                step = len(audio_data) // 500
                waveform = audio_data[::step][:500]
            else:
                waveform = audio_data
            
            # 基于真实音频特征的异常检测
            is_anomaly, anomaly_score = self.audio_detector.detect_anomaly(audio_file)
            
            return {
                'waveform': waveform.tolist(),
                'energy': energy,
                'peak_amplitude': peak_amplitude,
                'is_anomaly': is_anomaly,
                'anomaly_score': anomaly_score,
                'sample_rate': sample_rate,
                'duration': len(audio_data) / sample_rate if sample_rate > 0 else 0
            }
            
        except Exception as e:
            self.logger.error(f"音频文件分析失败: {e}")
            return {
                'waveform': self._generate_simulated_audio_waveform(),
                'energy': 0.01,
                'peak_amplitude': 0.1,
                'is_anomaly': False,
                'anomaly_score': 0.2
            }
    
    def _generate_simulated_audio_waveform(self):
        """生成模拟音频波形"""
        waveform = []
        for i in range(200):
            t = i * 0.01
            # 生成复合波形（基频 + 谐波）
            amplitude = (math.sin(2 * math.pi * 440 * t) * 0.6 +  # 基频
                        math.sin(2 * math.pi * 880 * t) * 0.3 +   # 二次谐波
                        random.uniform(-0.1, 0.1))                # 噪声
            waveform.append(amplitude)
        return waveform'''
    
    # 应用修复
    import re
    
    # 替换振动监控方法
    content = re.sub(r'    def vibration_monitor\(self\):.*?(?=\n    def [a-zA-Z_]|\nclass |\n\Z)', 
                     real_vibration_monitor, content, flags=re.DOTALL)
    
    # 替换音频监控方法
    content = re.sub(r'    def audio_monitor\(self\):.*?(?=\n    def [a-zA-Z_]|\nclass |\n\Z)', 
                     real_audio_monitor, content, flags=re.DOTALL)
    
    # 更新启动信息
    startup_info = '''    print("=== 真实数据采集版轴承监控系统 ===")
    print("🔧 主要特性:")
    print("1. 🌐 新IP地址: 192.168.10.101:5006")
    print("2. 📊 真实IMU振动数据采集 (MAC: 26:EF:60:96:87:3A)")
    print("3. 🔊 真实声音波形数据采集")
    print("4. 🎯 改进的异常检测算法")
    print("5. 📈 XYZ三轴振动实时显示")
    print("6. 🎵 声音波形图(类似Audacity)")
    print()'''
    
    content = content.replace('print("=== 真实声音异常检测错误: 无法获取振动数据===", re.DOTALL)', startup_info.strip())
    
    # 写入新版本
    with open('web_bearing_monitor_real_data.py', 'w', encoding='utf-8') as f:
        f.write(content)
    
    print("✅ 真实数据采集版本创建完成！")
    print("\n🔧 主要改进:")
    print("1. ✅ 更新IP地址为192.168.10.101")
    print("2. ✅ 实现真实IMU振动数据采集")
    print("3. ✅ 实现真实声音波形数据采集")
    print("4. ✅ 改进音频异常检测算法")
    print("5. ✅ 增加数据来源标识(真实/模拟)")

if __name__ == "__main__":
    create_real_data_version()